<style lang='less'>
</style>
<template>
  <div class="h-panel frame-page">
    <div class="h-panel-bar">
      <span class="h-panel-title">代码编辑器</span>
    </div>
    <div class="h-panel-bar">
      <Row :space="9">
        <Cell width="6">
          <div class="h-input-group">
            <Select v-model="table" :datas="tables" :filterable="true" @input="selectChange" placeholder="请选择数据表"></Select><Button><i class="icon-server"></i></Button>
          </div>
        </Cell>
        <Cell width="6">
          <div class="h-input-group">
            <Select v-model="likeField" :datas="cols" :filterable="true" placeholder="模糊搜索字段"></Select><Button><i class="icon-search"></i></Button>
          </div>
        </Cell>        
        <Cell width="6">
          <div class="h-input-group">
          <Select v-model="parentKey" :datas="cols" :filterable="true" placeholder="父级字段(Tree)"></Select><Button><i class="icon-folder"></i></Button>
          </div>
        </Cell>
        <Cell width="6">
          <div class="h-input-group">
          <Select v-model="parent_id" :datas="menus" placeholder="父级菜单"></Select><Button><i class="icon-archive"></i></Button>
          </div>
        </Cell>
        <Cell width="6">
          <div class="h-input-group">
          <input type="text" style="width:100%" v-model="menuName" placeholder="菜单名称" /><Button><i class="icon-tag"></i></Button>
        </div>
        </Cell>
        <Cell width="6">
          <SwitchList v-model="codeName" :datas="params"></SwitchList>
        </Cell>
        <Cell width="6">
          <Poptip v-if="table" content="确认生成代码?" @confirm="generate">
            <Button color="primary">生成代码</Button>
          </Poptip>
        </Cell>
      </Row>
    </div>
    <div class="h-panel-body">
      <Table :datas="columns" :height="300">          
          <TableItem title="Field" prop="Field"></TableItem>
          <TableItem title="标题">
            <template slot-scope="{data}">
              <input type="text" v-model="data.Comment" style="width:150px;" />
            </template>
          </TableItem>          
          <TableItem title="Type" prop="Type"></TableItem>
          <TableItem title="表单">
            <template slot-scope="{data}">
              <Select v-model="data.Key" :datas="keys"></Select>
            </template>
          </TableItem>
          <TableItem title="关联表">
            <template slot-scope="{data}">
              <Select v-model="data.relation" :datas="tables" :filterable="true" @input="relationSelect(data)" v-if="data.Key=='select'"></Select>
            </template>
          </TableItem>
          <TableItem title="显示字段">
            <template slot-scope="{data}">
              <Select v-model="data.relation_field" :datas="data.relation_fields" :filterable="true" v-if="data.Key=='select' && data.relation"></Select>
            </template>
          </TableItem>
          <TableItem title="列表显示">
            <template slot-scope="{data}">
              <h-switch v-model="data.status" :small="true">
                <span slot="open" class="h-icon-check"></span>
                <span slot="close" class="h-icon-close"></span>
              </h-switch>
            </template>
          </TableItem>
         
          <div slot="empty">暂无数据</div>
        </Table>
    </div>
    <div class="h-panel-body" v-if="table">
      <CodeEditor v-show="codeName=='list.vue'" v-model="listCode" mode="markdown" :readOnly="true"/>
      <CodeEditor v-show="codeName=='form.vue'" v-model="formCode" mode="markdown" :readOnly="true"/>
      <CodeEditor v-show="codeName=='detail.vue'" v-model="detailCode" mode="markdown" :readOnly="true"/>
      <CodeEditor v-show="codeName=='php'" v-model="phpCode" mode="markdown" :readOnly="true"/>
    </div>
  </div>
</template>
<script>
import _ from 'lodash'
import phpTemplate from 'components/demo-components/components/templates/php';
import listTemplate from 'components/demo-components/components/templates/list';
import detailTemplate from 'components/demo-components/components/templates/detail';
import formTemplate from 'components/demo-components/components/templates/form';

export default {
  data() {
    return {
      tables: [],
      parent_id:0,
      can:false,
      menuName:'',
      likeField:'',
      parentKey:'',
      table: '',
      codeName:'list.vue',
      params:['list.vue','form.vue','detail.vue','php'],
      menus:[],
      keys: [{
        title:'主键',
        key:'PRI'
      },{
        title:'文本',
        key:'input'
      },{
        title:'数字',
        key:'numberinput'
      },{
        title:'长文本',
        key:'textarea'
      },{
        title:'标签',
        key:'tags'
      },{
        title:'图片',
        key:'image'
      },{
        title:'下拉框',
        key:'select'
      },{
        title:'开关',
        key:'switch'
      },{
        title:'日期选择',
        key:'datepicker'
      },{
        title:'日期范围',
        key:'daterangepicker'
      },{
        title:'颜色选择器',
        key:'colorpicker'
      }],
      cols:[],
      columns: [],
      value: `'let a = 1;
       a=sa
`,
      mode: 'javascript',
      phpTemplate,listTemplate,detailTemplate,formTemplate,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init(){
      R.Tool.tables().then(resp=>{
        this.tables = resp.data
      });
      R.adminMenu.dict().then(resp=>{
        this.menus = resp.data
      });
    },
    relationSelect(data){
      log(data);
      if(!data.relation){
        data.relation_field = '';
        data.relation_fields = [];
        return false;
      }
      R.Tool.columns({table:data.relation}).then(resp=>{
        data.relation_fields = resp.data.map(column=>{
          return {title:column.Field,key:column.Field};
        });
      });
    },
    selectChange(table){
      if(!table){
        this.columns = [];
        return false;
      }
      R.Tool.columns({table}).then(resp=>{
        let columns = resp.data;
        let filters = ['updated_at','deleted_at'];
        let cols = [];
        columns.forEach(column=>{
           cols.push({title:column.Field,key:column.Field});
           column.relation = '';
           column.relation_field = '';
           column.relation_fields = [];
           column.status = !filters.includes(column.Field);
           if(!column.Key){
            if(column.Type.indexOf('varchar')>-1){
              column.Key = 'input';
            }else if(column.Type.indexOf('text')>-1){
              column.Key = 'textarea';
            }else if(column.Type.indexOf('int')>-1){
              column.Key = 'numberinput';
            }

            if(column.Field == 'pic'){
              column.Key = 'image';
            }else if(column.Field == 'status'){
              column.Key = 'switch';
            }else if(column.Field == 'type'){
              column.Key = 'select';
            }else if(column.Field.indexOf('_id')>0){
              column.Key = 'select';
            }

           }
        });
        this.cols = cols;
        this.columns = columns
      });
    },
    generate() {
      let params = {};
      if(!this.menuName){
        this.$Message.warn('请输入菜单名称');
        return false;
      }
      params.php = this.phpCode;
      params.list = this.listCode;
      params.form = this.formCode;
      params.detail = this.detailCode;
      params.parent_id = this.parent_id;
      params.name = this.menuName;
      params.table = _.upperFirst(_.camelCase(this.table));
      R.Tool.generate(params).then(resp=>{
        if(resp.code==200){
          this.$Message.success(resp.message);
        }else{
          this.$Message.warn(resp.message);
        }
      });
    }
  },
  computed: {
    detailCode:{
      get(){
        var tpl = this.detailTemplate;
let formItems = [];
let filters = ['deleted_at'];
this.columns.forEach(column=>{   
  if(!filters.includes(column.Field)){           
    let tmp = `<FormItem label="${column.Comment}：">{{data.${column.Field}}}</FormItem>`;
    if(column.Key == 'switch'){
      tmp = `<FormItem label="${column.Comment}："><button v-if="data.${column.Field}" type="button" class="h-btn h-btn-text-primary h-btn-no-border"><span>是</span></button>
  <button v-else type="button" class="h-btn h-btn-text-red h-btn-no-border"><span>否</span></button></FormItem>`;
    }else if(column.Key == 'select'){
      if(column.relation && column.relation_field){
        let name = column.Field.replace('_id','');
        tmp = `<FormItem label="${column.Comment}：">{{data.${name}.${column.relation_field}}}</FormItem>`;
      }      
    }else if(column.Key == 'image'){
      tmp = `<FormItem label="${column.Comment}："><img :src="data.${column.Field}" /></FormItem>`;
    }
    formItems.push(tmp);
  }
});
return tpl.replace('<!--formItems-->',formItems.join("\n")).replaceAll('====','');
      },
      set(){

      }
    },
    phpCode:{
      get(){
        var tpl = this.phpTemplate;
        let deleted_at = 'false';
        let relationItems = [];
        this.columns.forEach((col)=>{
          if(col.Field=='deleted_at'){
            deleted_at = 'true';
          }
          if(col.Key == 'select' && col.relation){
            let as = col.Field.replace('_id','');
            let relation_field = col.relation_field || '';
            if(col.relation_fields.length>1 && !relation_field){
              relation_field = col.relation_fields[1].key;
            }
            let deleted_at = '';
            let deleted_at_find = col.relation_fields.filter(item=>{return item.key=='deleted_at';});
            if(deleted_at_find.length==1){
              deleted_at = `'deleted_at'=>null`;
            }
            relationItems.push(`'${col.Field}' => ['table'=>'${col.relation}','as'=>'${as}','pri'=>'id','cols'=>['id','${relation_field}'],'where'=>[${deleted_at}],'type'=>'one'],`);
          }
        });
        let controllerName = _.upperFirst(_.camelCase(this.table))+'Controller';
        if(this.parentKey){
          tpl = tpl.replace('treeOpener','true').replace('pid',this.parentKey);
        }else{
          tpl = tpl.replace('treeOpener','false');
        }
        if(this.likeField){
          tpl = tpl.replace('title',this.likeField);
        }
        return tpl.replace('ControllerName',controllerName).replace('tblName',this.table).replace('bool',deleted_at).replace('<!--relationItems-->',relationItems.join("\n"));
      },
      set(){

      }
    },
    // form.vue
    formCode:{
      get(){
        var tpl = this.formTemplate;
        let formItems = [];
        let dictItems = [];
        let dictMethods = [];
        let filters = ['id','created_at','updated_at','deleted_at'];
        let requiredItems = [];
        let findImg = false;
        this.columns.forEach(column=>{         
          if(column.Key == 'image'){
            findImg = true;
          }
          if(!filters.includes(column.Field) && column.Key){ 
            requiredItems.push(`'${column.Field}'`);
            console.log(column.Key)           
            let tmp = `<FormItem label="${column.Comment}" prop="${column.Field}">
          <input type="text" v-model="data.${column.Field}" />
        </FormItem>`;
            if(column.Key == 'switch'){
              tmp = `<FormItem label="${column.Comment}" prop="${column.Field}">
          <h-switch :small="true" v-model="data.${column.Field}" />
          </h-switch>
        </FormItem>`;
            }else if(column.Key == 'tags'){
              tmp = `<FormItem label="${column.Comment}" prop="${column.Field}">
          <TagInput v-model="data.${column.Field}" :limit="10" :wordlimit="20"></TagInput>
        </FormItem>`;
            }else if(column.Key == 'numberinput'){
              tmp = `<FormItem label="${column.Comment}" prop="${column.Field}">
          <NumberInput v-model="data.${column.Field}" :precision="0"></NumberInput>
        </FormItem>`;
            }else if(column.Key == 'colorpicker'){
              tmp = `<FormItem label="${column.Comment}" prop="${column.Field}">
          <ColorPicker v-model="data.${column.Field}"></ColorPicker>
        </FormItem>`;
            }else if(column.Key == 'datepicker'){
              tmp = `<FormItem label="${column.Comment}" prop="${column.Field}">
          <DatePicker v-model="data.${column.Field}" format="YYYY-MM-DD"></DatePicker>
        </FormItem>`;
            }else if(column.Key == 'daterangepicker'){
              tmp = `<FormItem label="${column.Comment}" prop="${column.Field}">
          <DateRangePicker v-model="data.${column.Field}" format="YYYY-MM-DD"></DateRangePicker>
        </FormItem>`;
            }else if(column.Key == 'select'){
              let name = column.Field.replace('_id','');
              tmp = `<FormItem label="${column.Comment}" prop="${column.Field}">
          <Select v-model="data.${column.Field}" :datas="dict" :filterable="true"></Select>
        </FormItem>`;
              console.log(column.relation);
              if(column.relation){
                let relation = _.camelCase(column.relation);
                tmp = `<FormItem label="${column.Comment}" prop="${column.Field}">
          <Select v-model="data.${column.Field}" :datas="${relation}" :filterable="true"></Select>
        </FormItem>`;
                dictItems.push(`${relation}:[],`);
                dictMethods.push(`R.${relation}.dict().then(resp=>{
                  this.${relation} = resp.data;
                });`);
              }
            }else if(column.Key=='image'){
              tmp = `<FormItem label="${column.Comment}" prop="${column.Field}">
          <Oss :options="options" type="image" data-type="url" v-model="data.${column.Field}"></Oss>
        </FormItem>`;
            }

            formItems.push(tmp);
          }
        });
        let tableName = _.camelCase(this.table);   
        if(!findImg){
          tpl = tpl.replace("import oss from 'components/common/oss';","").replace("Oss: oss","");
        }    
        return tpl.replace('<!--formItems-->',formItems.join("\n"))
          .replace('<!--dictItems-->',dictItems.join("\n"))
          .replaceAll('R.Cate','R.'+tableName)
          .replace('<!--dictMethods-->',dictMethods.join("\n"))
          .replace('<!--requiredItems-->',requiredItems.join(","))          
          .replaceAll('====','');
      },
      set(){

      }
    },
    // 列表页list.vue代码
    listCode:{
      get:function(){
        if(this.columns.length==0){
          return '11';
        }
        let tableItems = [];
        let filters = ['updated_at','deleted_at'];
        let columnsItems = [];
        let params = {};
        this.columns.forEach(column=>{     
          if(!filters.includes(column.Field)){    
            params[column.Field] = '';        
            let tmp = `<TableItem title="${column.Comment}" prop="${column.Field}" sortProp="${column.Field}" :width="checkItemWidth('${column.Field}')" :sort="checkItemSort('${column.Field}')" v-if="checkItemShow('${column.Field}')"></TableItem>`;
            if(column.Field == 'status' || column.Field == 'show' || column.Field == 'state' || column.Key == 'switch'){
              params[column.Field] = false;
              tmp = `<TableItem title="状态" sortProp="${column.Field}" :width="checkItemWidth('${column.Field}')" :sort="checkItemSort('${column.Field}')" v-if="checkItemShow('${column.Field}')">
              <template slot-scope="{data}">
                <h-switch v-model="data.${column.Field}" :small="true" @input="toggleStatus(data,'${column.Field}')">
                  <span slot="open" class="h-icon-check"></span>
                  <span slot="close" class="h-icon-close"></span>
                </h-switch>
              </template>
            </TableItem>`;
            }else if(column.Field.indexOf('_id')>0){
              params[column.Field] = 0;
              let name = column.Field.replace('_id','');
              let title = column.relation_field;
              if(title){
                tmp = `<TableItem title="${column.Comment}" sortProp="${column.Field}" :width="checkItemWidth('${column.Field}')" :sort="checkItemSort('${column.Field}')" v-if="checkItemShow('${column.Field}')">
              <template slot-scope="{data}">
                <span>{{data.${name}?data.${name}.${title}:''}}</span>
              </template>
            </TableItem>`;
              }              
            }else if(column.Field == 'pic' || column.Field == 'logo' || column.Key=='image'){
              tmp = `<TableItem title="${column.Comment}" sortProp="${column.Field}" :width="checkItemWidth('${column.Field}')" :sort="checkItemSort('${column.Field}')" v-if="checkItemShow('${column.Field}')">
            <template slot-scope="{data}">
              <Avatar @click="imagePreview(data.${column.Field})" :src="data.${column.Field}" shape="square" noInfo></Avatar>
            </template>
          </TableItem>`;
            }else if(column.Field == 'tags'){
              params[column.Field] = [];
            }else if(column.Key == 'textarea'){
              tmp = `<TableItem title="${column.Comment}" sortProp="${column.Field}" :width="checkItemWidth('${column.Field}')" :sort="checkItemSort('${column.Field}')" v-if="checkItemShow('${column.Field}')"><template slot-scope="{data}">
              <TextEllipsis :text="data.${column.Field}" :height="40"  :isLimitHeight="true"><template slot="more"><span>...</span></template></TextEllipsis>
            </template></TableItem>`;
            }        

            if(this.parentKey && this.likeField == column.Field){
              tmp = `<TableItem title="${column.Comment}" prop="${column.Field}" sortProp="${column.Field}" :width="checkItemWidth('${column.Field}')" :sort="checkItemSort('${column.Field}')" v-if="checkItemShow('${column.Field}')" treeOpener></TableItem>`;
            }    
            tableItems.push(tmp);
          }
        });

        let formItems = [];
        let dictItems = [];
        let dictMethods = [];
        filters = ['updated_at','deleted_at'];
        this.columns.forEach(column=>{   
          if(!filters.includes(column.Field)){
            let width = 150;
            let is_sort = 'false';
            if(column.Key == 'PRI'){
              is_sort = 'true';
              width = 50;
            }else if(column.Key == 'textarea'){
              width = 300;
            }else if(column.Key == 'numberinput' || column.Key == 'switch'){
              width = 100;
            }
            columnsItems.push(`{Field:'${column.Field}',title:'${column.Comment?column.Comment:column.Field}',is_hidden:${!column.status},is_sort:${is_sort},width:${width}}`);        
          }
          if(!filters.includes(column.Field) && column.Key){           
            let tmp = `<Cell :xs='24' :sm='12' :md='8' :lg='6' :xl='6'><FormItem label="${column.Comment}" prop="${column.Field}">
          <input type="text" v-model="params.${column.Field}" />
        </FormItem></Cell>`;
            if(column.Key == 'switch'){
              tmp = `<Cell :xs='24' :sm='12' :md='8' :lg='6' :xl='6'><FormItem label="${column.Comment}" prop="${column.Field}">
          <HSwitch v-model="params.${column.Field}" trueValue="1" falseValue="0"/>
          </HSwitch>
        </FormItem></Cell>`;
            }else if(column.Key == 'select'){
              let name = column.Field.replace('_id','');
              tmp = `<Cell :xs='24' :sm='12' :md='8' :lg='6' :xl='6'><FormItem label="${column.Comment}" prop="${column.Field}">
          <Select v-model="params.${column.Field}" :datas="dict" :filterable="true"></Select>
        </FormItem></Cell>`;
              if(column.relation){
                let relation = _.camelCase(column.relation);
                tmp = `<Cell :xs='24' :sm='12' :md='8' :lg='6' :xl='6'><FormItem label="${column.Comment}" prop="${column.Field}">
          <Select v-model="params.${column.Field}" :datas="${relation}" :filterable="true"></Select>
        </FormItem></Cell>`;
                dictItems.push(`${relation}:[],`);
                dictMethods.push(`R.${relation}.dict().then(resp=>{
                  this.${relation} = resp.data;
                });`);
              }
            }
            if(column.Key != 'image'){
              formItems.push(tmp);
            }
          }
        });

        let tableName = _.camelCase(this.table);
        return this.listTemplate.replace('<!--tableItems-->',tableItems.join("\n"))
          .replaceAll('R.Cate','R.'+tableName)
          .replace('<!--columns-->',columnsItems.join(","))
          .replace('<!--formItems-->',formItems.join("\n"))
          .replace('<!--dictItems-->',dictItems.join("\n"))
          .replace('<!--dictMethods-->',dictMethods.join("\n"))
          .replace('<!--emptyParam-->',JSON.stringify(params))
          .replaceAll('====','');
      },
     set:function(){

     } 


    }
  }
};
</script>
